package com.e7.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

public class Captchar {
	private int width = 65;
	private int height = 28;
	private String captcha;
	public Captchar() {
	}
	public Captchar(int width, int height, String captcha) {
		this.width = width > 65 ? width : this.width;
		this.height = height > 65 ? height : this.height;
		this.captcha = captcha;
	}

	public void writeTo(ImageOutputStream imageOut) throws IOException {
		if (width <= 0)
			width = 65;
		if (height <= 0)
			height = 28;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, width, height);
		g.setColor(Color.black);
		g.drawRect(0, 0, width - 1, height - 1);
		g.setColor(Color.black);
		g.setFont(new Font("Atlantic Inline", Font.BOLD, 22));
		g.drawString(captcha.substring(0, 1), 8, 21);
		g.drawString(captcha.substring(1, 2), 22, 15);
		g.drawString(captcha.substring(2, 3), 38, 25);
		g.drawString(captcha.substring(3, 4), 49, 17);
		Random rand = new Random();
		for (int i = 0; i < 20; i++) {
			int x = rand.nextInt(width);
			int y = rand.nextInt(height);
			g.fillOval(x, y, x % 8, y % 7);
		}
		g.dispose();
		ImageIO.write(image, "JPEG", imageOut);
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}
}
